package com.example.spring_boot_demo.interceptor;

import com.example.spring_boot_demo.commons.enums.TokenEnum;
import com.example.spring_boot_demo.dto.User;
import com.example.spring_boot_demo.mapper.UserMapper;
import com.example.spring_boot_demo.utils.AjaxResult;
import com.example.spring_boot_demo.utils.HttpStatus;
import com.example.spring_boot_demo.utils.JWTUtil;
import com.example.spring_boot_demo.utils.UserThreadLocalUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <P> Description:
 */
@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    /**
     * 调用controller之前执行代码
     * 返回值true 表示放行 false表示拦截
     * 拦截器会拦截那些请求:普通请求、静态资源
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token = request.getHeader("authorization");
        log.info("获取到token:{}", token);
        if (token == null ||
                token.length() == 0 ||
                "null".equals(token) ||
                JWTUtil.verify(token).equals((TokenEnum.TOKEN_BAD))) {

            response.setContentType("application/json;charset=utf-8");

            String data = new ObjectMapper()
                    .writeValueAsString
                            (AjaxResult.error(HttpStatus.SEE_OTHER, "token 异常 重新登录"));
            log.info("token异常 重定向:{}", token);
            response.getWriter().write(data);
            return false;
        }
        Integer uid = JWTUtil.getUid(token);
        User user = userMapper.findUserById(uid);
        UserThreadLocalUtils.setUser(user);
        return true;
    }
}
